package com.study.lease.common.utils;

import com.study.lease.common.exception.LeaseException;
import com.study.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * description: JWT工具类
 * 作用：封装jwt生成token和校验token的代码
 */
public class JwtUtil {

    //private static long tokenExpiration = 24 * 365 * 60 * 60 * 1000L; // token过期时间：1nian
    private static long tokenExpiration = 60 * 60 * 1000L; // token过期时间：1nian
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

    public static String createToken(Long userId, String username) {
        String token = Jwts.builder().
                setSubject("LOGIN_USER").
                setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).
                claim("userId", userId).
                claim("username", username).
                signWith(tokenSignKey, SignatureAlgorithm.HS256).
                compact();
        return token;
    }

    /**
     * 为所有受保护的接口增加校验jwt合法性的逻辑
     * @param token
     * @return
     */
    public static Claims parseToken(String token){

        if (token==null){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH.getCode(),ResultCodeEnum.ADMIN_LOGIN_AUTH.getMessage());
        }

        try{
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(tokenSignKey).build();
            return jwtParser.parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e){
            // token过期
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED.getCode(), ResultCodeEnum.TOKEN_EXPIRED.getMessage());
        }catch (JwtException e){
            // token非法
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID.getCode(), ResultCodeEnum.TOKEN_INVALID.getMessage());
        }
    }
    //测试
    public static void main(String[] args) {
        String token = createToken(8L, "18738978721");
        System.out.println(token);
    }
}